import { AppName } from '../../app.config.js';
import path from 'path';
import fs from 'fs';
import Show from '../../model/show.js';
import puppeteer from '../../../../lib/puppeteer/puppeteer.js';
import data from '../../model/sanguoData.js'
//插件根目录
const __dirname = path.resolve() + path.sep + 'plugins' + path.sep + AppName;
// 文件存放路径
export const __PATH = {
  //用户数据
  player_path: path.join(__dirname, '/resources/data/sanguo_player'),
  //装备
  equipment_path: path.join(__dirname, '/resources/data/sanguo_equipment'),
  //包
  bag_path: path.join(__dirname, '/resources/data/sanguo_bag'),
  guojia: path.join(__dirname, '/resources/data/guojia/'),
  guojia1: path.join(__dirname, '/resources/data/guojia/曹魏.json'),
  guojia2: path.join(__dirname, '/resources/data/guojia/东吴.json'),
  guojia3: path.join(__dirname, '/resources/data/guojia/蜀汉.json'),
  master: path.join(__dirname, '/resources/data/yaml/master.yaml'),
};
import yaml from 'js-yaml';
let yamltype ={
  "1":__PATH.master,
}
let type ={
    "1":__PATH.player_path,
    "2":__PATH.equipment_path,
    "3":__PATH.bag_path,
}
let guojia={
    "1":__PATH.guojia1,//曹魏
    "2":__PATH.guojia2,//东吴
    "3":__PATH.guojia3,//蜀汉
}
/**
 *
 * @param num [1:player 2:equipment 3:bag]
 * @returns 
 */
export async function existplayer(num,usr_qq) {
    // let type ={
    //     "1":__PATH.player_path,
    //     "2":__PATH.equipment_path,
    //     "3":__PATH.bag_path
    // }
    let exist_player;
    exist_player = fs.existsSync(`${type[num]}/${usr_qq}.json`);
    if (exist_player) {
      return true;
    }
    return false;
  }
  /**
 *
 * @param num [1:player 2:equipment 3:bag]
 * @returns 
 */
  export async function Read_player(num,usr_qq) {
    let playerPath =`${type[num]}/${usr_qq}.json`
    
    //根据长度判读是否是分身
    let dir = path.join(playerPath);
    let player = fs.readFileSync(dir, 'utf8', (err, data) => {
      if (err) {
        console.log(err);
        return 'error';
      }
      return data;
    });
    //将字符串数据转变成数组格式
    player = JSON.parse(player);
    return player;
  }
  /**
 *
 * @param num [1:曹魏 2:东吴 3:蜀汉]
 * @returns 
 */
  export async function Read_json(num) {
    let playerPath =`${guojia[num]}`
    //根据长度判读是否是分身
    let dir = path.join(playerPath);
    let player = fs.readFileSync(dir, 'utf8', (err, data) => {
      if (err) {
        console.log(err);
        return 'error';
      }
      return data;
    });
    //将字符串数据转变成数组格式
    player = JSON.parse(player);
    return player;
  }
  /**
 *
 * @param num [1:player 2:equipment 3:bag]
 * @returns 
 */
  export async function Write_player(num,usr_qq, player) {
    let dir = path.join(type[num], `${usr_qq}.json`);
    let new_ARR = JSON.stringify(player, '', '\t');
    fs.writeFileSync(dir, new_ARR, 'utf8', err => {
      console.log('写入成功', err);
    });
    return;
  }
   /**
 *
 * @param num [1:曹魏 2:东吴 3:蜀汉]
 * @returns 
 */
   export async function Write_json(num,json) {
    let dir = path.join(guojia[num]);
    let new_ARR = JSON.stringify(json, '', '\t');
    fs.writeFileSync(dir, new_ARR, 'utf8', err => {
      console.log('写入成功', err);
    });
    return;
  }
//   let type2={
//     1:"HP"
//   }
   /**
 *
 * @param num [1:HP]
 * @returns 
 */
  export async function Add_player(num,usr_qq, blood = 0) {
    if (num === 1) {
        let player = await Read_player(1,usr_qq);
        player.当前血量 += Math.trunc(blood);
        if (player.当前血量 > player.血量上限) {
        player.当前血量 = player.血量上限;
        }
        if (player.当前血量 < 0) {
        player.当前血量 = 0;
        }
        await Write_player(1,usr_qq, player);
        return;
    }
    
  }
  export async function getPlayerAction(usr_qq) {
    //查询redis中的人物动作
    let arr = {};
    let action = await redis.get(`sanguo:player:${usr_qq}:action`);
    action = JSON.parse(action);
    let now_time = new Date().getTime();
    //动作不为空闲
    if (action != null) {
      if("禁闭" == action.action){
        if(null != action.end_time){
          if(0 <= now_time - action.end_time ){
            await redis.del('xiuxian:player:' + usr_qq + ':action');
            arr.action = '空闲';
            return arr;
          }else{
            let time = action.end_time - now_time;
            let days = parseInt(time / (1000 * 60 * 60 * 24));
            let hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            let minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
            arr.action = action.action;
            arr.time = days + " 天 " + hours + " 小时 " + minutes + " 分钟 ";
            return arr;
          }
        }
      }
      if(null != action.start_time){
        let time = now_time - action.start_time
        let days = parseInt(time / (1000 * 60 * 60 * 24));
        let hours = parseInt((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        let minutes = parseInt((time % (1000 * 60 * 60)) / (1000 * 60));
        arr.action = action.action;
        arr.time = days + " 天 " + hours + " 小时 " + minutes + " 分钟 ";
        return arr;
      }
    }
    arr.action = '空闲';
    return arr;
  }
  export async function get_player_img(e,usr_qq) {
    let 法宝评级;
    let 护具评级;
    let 武器评级;
    let player = await Read_player(1,usr_qq)
    let equipment = await Read_player(2,usr_qq)
    let player_status = await getPlayerAction(usr_qq);
    let status = '空闲';
    if (player_status.time != null) {
      status = player_status.action + '(' + player_status.time + ')';
    }
    let lingshi = Math.trunc(player.金钱);
    if (player.金钱 > 999999999999) {
      lingshi = 999999999999;
    }
    if (player.宣言 == null || player.宣言 == undefined) {
      player.宣言 = '这个人很懒什么都没写';
    }
    await Write_player(1,usr_qq,player)
    if (!isNotNull(player.sex)) {
      e.reply('请先#一键同步');
      return;
    }
    let zd = ['攻击', '防御', '生命加成', '防御加成', '攻击加成'];
    let num = [];
    let p = [];
    let kxjs = [];
    let count = 0;
    for (let j of zd) {
      if (player[j] == 0) {
        p[count] = '';
        kxjs[count] = 0;
        count++;
        continue;
      }
      p[count] = Math.floor(Math.log(player[j]) / Math.LN10);
      num[count] = player[j] * 10 ** -p[count];
      kxjs[count] = `${num[count].toFixed(2)} x 10`;
      count++;
    }
    //境界名字需要查找境界名
    let pinji = ['劣', '普', '优', '精', '极', '绝', '顶'];
    if (!isNotNull(equipment.武器.pinji)) {
      武器评级 = '无';
    } else {
      武器评级 = pinji[equipment.武器.pinji];
    }
    if (!isNotNull(equipment.护具.pinji)) {
      护具评级 = '无';
    } else {
      护具评级 = pinji[equipment.护具.pinji];
    }
    if (!isNotNull(equipment.法宝.pinji)) {
      法宝评级 = '无';
    } else {
      法宝评级 = pinji[equipment.法宝.pinji];
    }
    let bao = parseInt(player.暴击率 * 100) + '%';
    equipment.武器.bao = parseInt(equipment.武器.bao * 100) + '%';
    equipment.护具.bao = parseInt(equipment.护具.bao * 100) + '%';
    equipment.法宝.bao = parseInt(equipment.法宝.bao * 100) + '%';
    let strand_hp = Strand(player.当前血量, player.血量上限);
    lingshi = bigNumberTransform(lingshi);
    let player_data = {
      user_id: usr_qq,
      player, // 玩家数据
      equipment, // 装备数据
      player_action: status, // 当前状态
      strand_hp,
      bao,
      nickname: player.名号,
      declaration: player.宣言,
      lingshi: lingshi,
      player_maxHP: player.血量上限,
      player_nowHP: player.当前血量,
      player_atk: kxjs[0],
      player_atk2: p[0],
      player_def: kxjs[1],
      player_def2: p[1],
      生命加成: kxjs[2],
      生命加成_t: p[2],
      防御加成: kxjs[3],
      防御加成_t: p[3],
      攻击加成: kxjs[4],
      攻击加成_t: p[4],
      player_bao: player.暴击率,
      player_bao2: player.暴击伤害,
      arms: equipment.武器,
      armor: equipment.护具,
      treasure: equipment.法宝,
      武器评级: 武器评级,
      护具评级: 护具评级,
      法宝评级: 法宝评级,
    };
    const data1 = await new Show(e).get_playerData(player_data);
    return await puppeteer.screenshot('player', {
      ...data1,
    });
  }
  export async function bigNumberTransform(value) {
    const newValue = ['', '', ''];
    let fr = 1000;
    let num = 3;
    let text1 = '';
    let fm = 1;
    while (value / fr >= 1) {
      fr *= 10;
      num += 1;
      // console.log('数字', value / fr, 'num:', num)
    }
    if (num <= 4) {
      // 千
      newValue[0] = parseInt(value / 1000) + '';
      newValue[1] = '千';
    } else if (num <= 8) {
      // 万
      text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万';
      // tslint:disable-next-line:no-shadowed-variable
      fm = text1 === '万' ? 10000 : 10000000;
      if (value % fm === 0) {
        newValue[0] = parseInt(value / fm) + '';
      } else {
        newValue[0] = parseFloat(value / fm).toFixed(2) + '';
      }
      newValue[1] = text1;
    } else if (num <= 16) {
      // 亿
      text1 = (num - 8) / 3 > 1 ? '千亿' : '亿';
      text1 = (num - 8) / 4 > 1 ? '万亿' : text1;
      text1 = (num - 8) / 7 > 1 ? '千万亿' : text1;
      // tslint:disable-next-line:no-shadowed-variable
      fm = 1;
      if (text1 === '亿') {
        fm = 100000000;
      } else if (text1 === '千亿') {
        fm = 100000000000;
      } else if (text1 === '万亿') {
        fm = 1000000000000;
      } else if (text1 === '千万亿') {
        fm = 1000000000000000;
      }
      if (value % fm === 0) {
        newValue[0] = parseInt(value / fm) + '';
      } else {
        newValue[0] = parseFloat(value / fm).toFixed(2) + '';
      }
      newValue[1] = text1;
    }
    if (value < 1000) {
      newValue[0] = value + '';
      newValue[1] = '';
    }
    return newValue.join('');
  }
  function Strand(now, max) {
    let num = ((now / max) * 100).toFixed(0);
    let mini;
    if (num > 100) {
      mini = 100;
    } else {
      mini = num;
    }
    let strand = {
      style: `style=width:${mini}%`,
      num: num,
    };
    return strand;
  }
  export async function isNotNull(obj) {
    return obj !== undefined && obj !== null;
  }
  export async function alluser() {
    let B = [];
    let A = fs
      .readdirSync(__PATH.player_path)
      .filter(file => file.endsWith('.json'));
    for (let item of A) B.push(item.substring(0, item.lastIndexOf('.')));
    return B;
  }
  export async function Go(e) {
    let usr_qq = e.user_id;
    //不开放私聊
    if (!e.isGroup) {
        return 0;
    }
    //有无存档
    let ifexistplay = await existplayer(1,usr_qq);
    if (!ifexistplay) {
        return 0;
    }
    //查询redis中的人物动作
    let action = await redis.get(`sanguo:player:${usr_qq}:action`);
    action = JSON.parse(action);
    let now_time = new Date().getTime();
    if (action != null) {
      if (null != action.start_time) {
        if ("打工" == action.action) {
              let m = parseInt((now_time -action.start_time) / 1000 / 60);
              let s = parseInt((now_time -action.start_time  - m * 60 * 1000) / 1000);
              e.reply(`正在` + action.action + '中，已过:' + m + '分' + s + '秒');
              return;
        }else if ("攻打副本" == action.action) {
           action.start_time+=action.time*60*1000
           if (action.start_time < now_time) {
              let m = parseInt((now_time -action.start_time) / 1000 / 60);
              let s = parseInt((now_time -action.start_time  - m * 60 * 1000) / 1000);
              e.reply(`正在` + action.action + '中，已过:' + m + '分' + s + '秒');
              return;
           }else if (action.start_time >= now_time) {
            
           }
        } 
          }
          
          }
           return true;
        }
        export async function Go2(e,num) {
          let usr_qq = e.user_id;
          //不开放私聊
          if (!e.isGroup) {
              return 0;
          }
          //有无存档
          let ifexistplay = await existplayer(1,usr_qq);
          if (!ifexistplay) {
              return 0;
          }
          //查询redis中的人物动作
          let action = await redis.get(`sanguo:${num}:${usr_qq}:action`);
          action = JSON.parse(action);
          let now_time = new Date().getTime();
          if (action != null) {
            if (null != action.start_time) {
             if ("攻打副本" == action.action) {
                 action.start_time+=action.time*60*1000
                 if (action.start_time > now_time) {
                   const timeDiff = action.start_time - now_time;
                   const minutes = Math.floor(timeDiff / 1000 / 60);
                   const seconds = Math.floor((timeDiff / 1000) % 60);
                    e.reply(`正在${action.action}中，还剩: ${minutes}分${seconds}秒`);
                   return;
                 }else if (action.start_time <= now_time) {
                   await action_way_fun(e,num)
                   return;
                 }
              } 
                }
                
                }
                 return true;
              }
          export async function Go3(e,guojia) {
                let usr_qq = e.user_id;
                if (!e.isGroup) return 0;
                //有无存档
                if (!await existplayer(1,usr_qq)) return 0;
                //查询redis中的人物动作
                let action = await redis.get(`sanguo:${guojia.name}:action`);
                action = JSON.parse(action);
                let now_time = new Date().getTime();
                if (action != null) {
                  if (null != action.start_time) {
                   if ("国家战争" == action.action) {
                       action.start_time+=action.time*60*1000
                       if (action.start_time > now_time) {
                         const timeDiff = action.start_time - now_time;
                         const minutes = Math.floor(timeDiff / 1000 / 60);
                         const seconds = Math.floor((timeDiff / 1000) % 60);
                          e.reply(`正在${action.action}中，还剩: ${minutes}分${seconds}秒`);
                         return;
                       }else if (action.start_time <= now_time) {
                         await action_way_fun2(e,guojia)
                         return;
                       }
                    } 
                      }
                      
                      }
                       return true;
                    }
        export async function action_way_fun2(e,guojia) {
          let usr_qq = e.user_id;
          let action = JSON.parse(await redis.get(`sanguo:${guojia.name}:action`));

          let guo = await getGuojia(action.guo1);
          let guo2 = await getGuojia(action.guo2);

          let zhanli1 = calculateZhanli(guo);
          let zhanli2 = calculateZhanli(guo2);
          
          console.log(`势力1战力：${zhanli1}`);
          console.log(`势力2战力：${zhanli2}`);

          function calculateZhanli(guo) {
            let zhanli = 0;
          
            guo.兵 = parseInt(guo.兵);
            guo.科技 = parseInt(guo.科技);
            zhanli += guo.兵 * 1000 * guo.科技;
          
            for (let i = 0; i < guo.普通兵种.length; i++) {
              zhanli += guo.普通兵种[i] * 2000;
            }
          
            let specialTroops = guo.特殊兵种;
            for (const [troopName, troopCount] of Object.entries(specialTroops)) {
              let count = parseInt(troopCount);
              if (troopName === "神射手" || troopName === "神剑兵" || troopName === "神矛兵") {
                zhanli += 3000 * count;
              } else {
                zhanli += 2500 * count;
              }
              console.log(`兵种名称：${troopName}`);
              console.log(`兵种数量：${count}`);
            }
          
            for (const wujiang of guo.武将) {
              wujiang.武力值 = parseInt(wujiang.武力值);
              wujiang.数量 = parseInt(wujiang.数量);
              zhanli += wujiang.武力值 * 100 * wujiang.数量;
            }
          
            let type = ["剑兵", "骑兵", "长矛兵", "弓兵"];
            let type2 = [
              "重骑兵",
              "骑射兵",
              "火弓兵",
              "弩弓兵",
              "神射手",
              "重剑兵",
              "轻剑兵",
              "神剑兵",
              "重矛兵",
              "神矛兵"
            ];
          
            for (const queue of guo.队伍) {
              for (const wujiang of queue.武将) {
                wujiang.武力值 = parseInt(wujiang.武力值);
                wujiang.数量 = parseInt(wujiang.数量);
                zhanli += wujiang.武力值 * wujiang.数量 * 100;
              }
          
              for (const [troopName, troopCount] of Object.entries(queue.兵种)) {
                let count = parseInt(troopCount);
                if (type.includes(troopName)) {
                  zhanli += 3000 * count;
                } else if (type2.includes(troopName)) {
                  zhanli += 2500 * count;
                } else {
                  console.log(`兵种名称：${troopName}`);
                  console.log(`兵种数量：${count}`);
                }
              }
            }
          
            return zhanli;
          }

          if (action.action ==="国家战争" ) {
            const random = Math.random();
            let msg = [];
            let tudi = action.tiaoyue.划分国土;
            let money = action.tiaoyue.赔偿金额;
            let a = guo.name
            let b = guo2.name
            let yue = guojia.条约.find(item => item.name =action.tiaoyue.name)
            if (zhanli1>zhanli2) {
              if(random<0.8){
                msg.push(`${a}胜利,获得土地${tudi},获得金钱${money}
                ${b}失败,损失土地${tudi},损失金额${money}`)
                yue.签订国 = b;
              }else if(random<0.6){
                msg.push(`敌方突然兴奋,战力暴涨,${b}胜利,获得土地${tudi},获得金钱${money}
                ${a}失败,损失土地${tudi},损失金额${money}`)
              }else if(random <0.4){
                msg.push(`蛮子突然入侵，发动技能南蛮入侵,${a}和${b}出杀,清理完蛮，然后继续打,最终${a}胜利,获得土地${tudi},获得金钱${money}
                ${b}失败,损失土地${tudi},损失金额${money}`)
                yue.签订国 = b;
              }else if(random <0.4){
                msg.push(`蛮子突然入侵，发动技能南蛮入侵,${a}和${b}出杀,清理完蛮，然后继续打,最终${b}胜利,获得土地${tudi},获得金钱${money}
                ${a}失败,损失土地${tudi},损失金额${money}`)
              }
            }else{
              if(random<0.8){
                msg.push(`${b}胜利,获得土地${tudi},获得金钱${money}
                ${a}失败,损失土地${tudi},损失金额${money}`)
              }else if(random<0.6){
                msg.push(`我方突然兴奋,战力暴涨,${a}胜利,获得土地${tudi},获得金钱${money}
                ${b}失败,损失土地${tudi},损失金额${money}`)
                yue.签订国 = b;
              }else if(random <0.4){
                msg.push(`蛮子突然入侵，发动技能南蛮入侵,${a}和${b}出杀,${a}在那里摸鱼的杀蛮,清理完蛮，然后继续打,最终${a}胜利,获得土地${tudi},获得金钱${money}
                ${b}失败,损失土地${tudi},损失金额${money}`)
                yue.签订国 = b;
              }else if(random <0.4){
                msg.push(`蛮子突然入侵，发动技能南蛮入侵,${a}和${b}出杀,清理完蛮，然后继续打,最终${b}胜利,获得土地${tudi},获得金钱${money}
                ${a}失败,损失土地${tudi},损失金额${money}`)
              }
            }
            if(yue.签订国 === b){
              guo.国库 += money
              guo.国土面积 += tudi
              guo2.国库 -= money
              guo2.国土面积 -= tudi
            }else{
              guo2.国库 += money
              guo2.国土面积 += tudi
              guo.国库 -= money
              guo.国土面积 -= tudi
          }
          await Write_json(await getGuojiaIndex(a), guo);
          await Write_json(await getGuojiaIndex(b), guo2);
          if(guo.负债 < 0) msg.push(`${a}国家已负债${guo.负债},请尽快还款`);
          if(guo2.负债<0 ) msg.push(`${b}国家已负债${guo2.负债},请尽快还款`);
          
          
          await redis.del(`sanguo:${a}:action`);
          //发送消息
          let temp_data = {
            temp: msg,
          };
          const data1 = await new Show().get_jiesuanData(temp_data);
          let img = await puppeteer.screenshot('jiesuan', {
            ...data1,
          });
          return e.reply(img);
          }
        } 
        // async function getPlayerAction(usr_qq) {
        //   const action = await redis.get(`xiuxian:player:${usr_qq}:action`);
        //   return JSON.parse(action);
        // }
        export async function getGuojia(guojiaName) {
          let guojiaIndex;
          if (guojiaName === "曹魏") {
            guojiaIndex = 1;
          } else if (guojiaName === '蜀汉') {
            guojiaIndex = 3;
          } else if (guojiaName === "东吴") {
            guojiaIndex = 2;
          }
          return await Read_json(guojiaIndex);
        }
      export async function getGuojiaIndex(guojiaName) {
          if (guojiaName === '曹魏') {
            return 1;
          } else if (guojiaName === '蜀汉') {
            return 3;
          } else if (guojiaName === '东吴') {
            return 2;
          }
        }
        export async function exist_json_thing(
          usr_qq,
          thing_name,
        ) {
          let player = await Read_player(1,usr_qq)
          let guojia = await getGuojia(player.国家)
          let ifexist;
            let type =[ 
              '武将',
            ];
            for (let i of type) {
              ifexist = guojia[i].find(item => item.name == thing_name);
              if (ifexist) break;
            }
          if (ifexist) {
            return ifexist.数量;
          }
          return false;
        }
       
   /**
 *
 * @param num [1:曹魏 2:东吴 3:蜀汉]
 * @returns 
 */
export async function exist_json(num) {
          let exist_player;
          exist_player = fs.existsSync(`${guojia[num]}`);
          if (exist_player) {
            return true;
          }
          return false;
        }
 /**
 *
 * @param num [曹魏 东吴 蜀汉]
 * @returns 
 */
 export async function Write_sanguo(num) {
          let guojia = {
            "name": num,
            "player": [],
            "人口": 0,
            "经济": 0,
            "科技": 0,
            "科技exp": 0,
            "兵力": 0,
            "兵": 0,
            "武将": [],
            "赋税": 0,
            "time": 0,
            "民心": 100,
            "time2":0,
            "队伍":[],
            "负债":0
          }
          let dir = path.join(`${__PATH.guojia}/${num}.json`);
          let new_ARR = JSON.stringify(guojia, '', '\t');
          fs.writeFileSync(dir, new_ARR, 'utf8', err => {
            console.log('写入成功', err);
          });
        }
  
/**
 * 增加减少纳戒内物品
 * @param usr_qq 操作存档的qq号
 * @param name  物品名称
 * @param thing_class  物品类别
 * @param x  操作的数量,取+增加,取 -减少
 * @returns 无
 * 
 */
export async function Add_json_thing(usr_qq, name, thing_class, x) {
  if (x == 0) return;
  let player = await Read_player(1,usr_qq)
  let guojia = await getGuojia(player.国家)
  let exist = await exist_json_thing(usr_qq, name, thing_class);
  if (x > 0 && !exist) {
    let thing;
    let list = [
      'wujiang_list',
    ];
    for (let i of list) {
      thing = data[i].find(item => item.name == name);
      if (thing) {
        guojia[thing_class].push(thing);
        guojia[thing_class].find(item => item.name == name).数量 = x;   
        await Write_json(await getGuojiaIndex(player.国家), guojia);
        return;
      }
    }
  }
  guojia[thing_class].find(item => item.name == name).数量 += x;
  guojia[thing_class] = guojia[thing_class].filter(item => item.数量 > 0);
  await Write_json(await getGuojiaIndex(player.国家), guojia);
  return;
}
export async function synchronization(e) {
  if (!e.isMaster) {
    return;
  }
  e.reply('存档开始同步');
  let playerList = [];
  let files = fs
      .readdirSync('./plugins/' + AppName + '/resources/data/sanguo_player')
      .filter(file => file.endsWith('.json'));
  for (let file of files) {
    file = file.replace('.json', '');
    playerList.push(file);
  }
  for (let i = 1; i <= 3; i++) {
    let guojia = await Read_json(i);
    let { player, 武将, 队伍,条约 } = guojia;
    let ziduan2 = [
      "人口",
      "经济",
      "科技",
      "科技exp",
      "兵力",
      "兵",
      "赋税",
      "time",
      "time2",
      "负债",
      "国库"
    ];
    let ziduan3 = ["民心"];
    let ziduan4 = ["国土面积"];
    
    [player, 武将, 队伍,条约].forEach((k) => {
      if (!k) {
        k = [];
      }
    });
  
    ziduan2.forEach((k) => {
      guojia[k] ??= 0;
    });
  
    ziduan3.forEach((k) => {
      guojia[k] ??= 100;
    });

    ziduan4.forEach((k) => {
      guojia[k] ??= 10000;
    });

    if (!guojia.普通兵种) {
      guojia.普通兵种 = [
        "剑兵",
        "骑兵",
        "长矛兵",
        "弓兵"
      ];
    }
    
    guojia.普通兵种 ??= {
      "剑兵": 0,
      "骑兵": 0,
      "长矛兵": 0,
      "弓兵": 0
    };
  
    guojia.特殊兵种 ??= {
      "重骑兵": 0,
      "骑射兵": 0,
      "火弓兵": 0,
      "弩弓兵": 0,
      "神射手": 0,
      "重剑兵": 0,
      "轻剑兵": 0,
      "神剑兵": 0,
      "重矛兵": 0,
      "神矛兵": 0
    };
  
    guojia.赋税 ??= 0;
    await Write_json(i, guojia);
  }
  for (let player_id of playerList) {
    let usr_qq = player_id;
    let player = await Read_player(1,usr_qq)
    let ziduan =["诗"]
    ziduan.forEach((k) => {
      guojia[k] ??= [];
    });
    await Write_player(1,usr_qq, player);
  }
  return e.reply(`同步完毕`);
}
/**
 *
 * @param num [1:master]
 * @returns 
 */
  export async function Read_yaml(num){
    try {
      const fileContents = fs.readFileSync(yamltype[num], 'utf8');
      const data = yaml.load(fileContents);
      return data;
      // 现在你可以使用 data 变量访问 YAML 文件中的数据
    } catch (error) {
      console.log(error);
    }
  }
  export async function Write_yaml(num,wyaml){
    try {
      // 将修改后的数据转换为 YAML 格式
      const yamlData = yaml.dump(wyaml);
      // 写入 YAML 文件
      fs.writeFileSync(yamltype[num], yamlData, 'utf8');
      console.log('YAML 文件写入成功！');
    } catch (error) {
      console.log(error);
    }
  }
  export async function jianmaster(e){
    const yaml = await Read_yaml(1);
    const usr_qq = e.user_id;
    const hasElement = yaml.master.includes(usr_qq);
    return e.isMaster && hasElement;
  }
  export async function getpaihangbang(e, weizhi) {
 // wujiang_list 是一个包含武将信息的数组，每个武将对象包含一个 武力值 属性表示战力
      let sortedList = [];

      // 将武将对象按照战力从高到低的顺序添加到 sortedList 数组中
      for (let i = 0; i < data.wujiang_list.length; i++) {
        const wujiang = data.wujiang_list[i];
        let inserted = false;

        for (let j = 0; j < sortedList.length; j++) {
          if (wujiang.武力值 > sortedList[j].武力值) {
            sortedList.splice(j, 0, wujiang);
            inserted = true;
            break;
          }
        }

        if (!inserted) {
          sortedList.push(wujiang);
        }
      }

      for (let i = 0; i < sortedList.length; i++) {
        const element = sortedList[i];
        element.powerRank = i + 1;
      }
      let get_data={fanjiedidian_list: sortedList,}
      const data1 = await new Show().get_paihangbangData(get_data);
      let img = await puppeteer.screenshot('paihangbang', {
        ...data1,
      });
      e.reply(img)
  } 
  export async function getfuben(e, weizhi) {
    let get_data={didian_list: weizhi,}
    const data1 = await new Show().get_fubenData(get_data);
    let img = await puppeteer.screenshot('fuben', {
      ...data1,
    });
    e.reply(img)

  } 
  /**
 * 增加减少纳戒内物品
 * @param currentDate 开始时间
 * @param time 需要时间
 * 
 */
  //判断是否过了time天
  export async function hasPassedOneDay(currentDate,time) {
      const currentTimeStamp = new Date().getTime()
      const nextDay =  currentDate + time * 24 * 60 * 60 * 1000
      return currentTimeStamp >= nextDay;
  }
  export  async function action_way_fun(e,shuzhi) {
    if (!e.isGroup) {
      return;
    }
    let usr_qq = e.user_id;
    //查看存档
    let ifexistplay = await existplayer(1,usr_qq);
    if (!ifexistplay) {
      return;
    }
    //查询redis中的人物动作
    let action = await redis.get(`sanguo:${shuzhi}:${usr_qq}:action`);
    action = JSON.parse(action);

    if (action != null) {
      let player = await Read_player(1,usr_qq);
      if('攻打副本' == action.action){

          let guojia = await getGuojia(player.国家)
          let weizhi = await data.fuben_list.find(item => item.name == action.fuben);
          const randomNumber = Math.random();
          let zhanli = 0
          zhanli+=action.bing*10000
          
          //   for (let i = 0; i <= action.wujiang.length; i++) {
          //     if(action.wujiang[i] = undefined){
          //       break
          //     }
          //     zhanli+=action.wujiang[i].武力值*10000
          //  }
          zhanli = action.wujiang.reduce((total, wujiang) => {
            if (!wujiang || typeof wujiang.武力值 === 'undefined') {
              return total;
            }
            return total + wujiang.武力值 * 10000;
          }, 0);
          const team = guojia.队伍.find(item => parseInt(item.编号) === parseInt(shuzhi));
          const 非零兵种列表 = Object.entries(team.兵种)
         .filter(([兵种名称, 数量]) => 数量 !== 0)
         .map(([兵种名称, 数量]) => 兵种名称);
         let type=["剑兵","骑兵","长矛兵","弓兵"]
         let type2=["重骑兵","骑射兵","火弓兵","弩弓兵","神射手","重剑兵","轻剑兵", "神剑兵","重矛兵","神矛兵"]
         console.log(非零兵种列表);
        if(非零兵种列表){
          for(let a = 0;a<type.length; a++){
            for (let i = 0; i < 非零兵种列表.length; i++) {
              for(let b = 0; b<type2.length;b++){
               if(非零兵种列表[i]=== type[a]){
                zhanli += team.兵种[非零兵种列表[i]]*15000
               }else if(非零兵种列表[i]=== type2[b]){
                zhanli += team.兵种[非零兵种列表[i]]*20000
               }
              }
          }}}
          
          let num = action.bing;
          let num2 = weizhi.金钱;
          let populationIncrease = Math.floor(Math.random() * (num * 0.5));
          let populationIncrease2 = Math.floor(Math.random() * (num2 * 0.1));
 
          let msg = [];
          
          if (weizhi.战力 >= zhanli) {
            if (randomNumber < 0.5) {
              populationIncrease2 += num2;
              populationIncrease = Math.floor(Math.random() * (num * 0.5));
             
              let msg1 = `你打的与对方难舍难分，最终取得胜利，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
              guojia.负债 += populationIncrease2;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                 for(let a = 0;a<type.length; a++){
                   for(let b = 0; b<type2.length;b++){
                      if(非零兵种列表[i]=== type[a]){
                        if (randomNumber<0.8) {
                          let x = team.兵种[非零兵种列表[i]]
                          let xx = Math.floor(Math.random() * (x* 0.5));
                          x-=xx
                          let msg2=`损失${非零兵种列表[i]}${xx}`
                          msg.push(msg2)
                        }
                       }else if(非零兵种列表[i]=== type2[b]){
                          if (randomNumber<0.4) {
                          let x = team.兵种[非零兵种列表[i]]
                          let xx = Math.floor(Math.random() * (x* 0.3));
                          x-=xx
                          let msg2=`损失${非零兵种列表[i]}${xx}`
                          msg.push(msg2)
                        }
                      }
                      let msg2=`其他兵种未损失`
                      msg.push(msg2)
                    }
                  }
               }
              return;
            } else {
              num2 *= 0.9;
              populationIncrease2 = Math.floor(Math.random() * num2);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `你打的与对方难舍难分，最终失败，损失兵马${populationIncrease}，损失金钱${populationIncrease2}`;
              guojia.负债 -= populationIncrease2;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
            }
            populationIncrease=parseInt(populationIncrease)
            team.兵=parseInt(team.兵)
            team.兵 -= populationIncrease;
          
            if (randomNumber < 0.3) {
              num *= 0.7;
              num2 *= 0.9;
              populationIncrease = Math.floor(Math.random() * num);
              populationIncrease2 = Math.floor(Math.random() * num2);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `与对方实力差距过大，损失大幅度增加，最终失败，损失兵马${populationIncrease}，损失金钱${populationIncrease2}`;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              populationIncrease=parseInt(populationIncrease)
              team.兵=parseInt(team.兵)
              team.兵 -= populationIncrease;
              guojia.负债 -= populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
              return;
            } else if (randomNumber < 0.3) {
              num *= 0.3;
              num2 *= 0.1;
              populationIncrease = Math.floor(Math.random() * num);
              populationIncrease2 = Math.floor(Math.random() * num2);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `我方士兵血气上涌，但你还是败了，最终取得胜利，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
               if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              populationIncrease=parseInt(populationIncrease)
              team.兵=parseInt(team.兵)
              team.兵 -= populationIncrease;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
              return;
            } else if (randomNumber < 0.4) {
              num *= 0.3;
              num2 *= 0.1;
              populationIncrease = Math.floor(Math.random() * num);
              populationIncrease2 = Math.floor(Math.random() * num2);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `我方士兵血气上涌，打败了对方，最终取得胜利，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              populationIncrease=parseInt(populationIncrease)
              team.兵=parseInt(team.兵)
              team.兵 -= populationIncrease;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }

            }              
            if (randomNumber < 0.1) {
              num2 *= 0.9;
              populationIncrease2 = Math.floor(Math.random() * num2);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `与对方实力悬殊过大，此时天降陨石，炸死了对方，未损失兵马，获得金钱${populationIncrease2}`;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
            }
          } else if (weizhi.战力 <= zhanli) {
            if (randomNumber < 0.7) {
              let populationIncrease = Math.floor(Math.random() * (num * 0.5));
              populationIncrease2 += num2;
              let msg1 = `你打的与对方难舍难分，最终取得胜利，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              populationIncrease=parseInt(populationIncrease)
              team.兵=parseInt(team.兵)
              team.兵 -= populationIncrease;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
            } else if (randomNumber < 0.5) {
              num *= 0.3;
              populationIncrease = Math.floor(Math.random() * num);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `你轻松的战胜了对手，大幅度减少了损失，最终取得胜利，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              team.兵=parseInt(team.兵)
              populationIncrease=parseInt(populationIncrease)
              team.兵 -= populationIncrease;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
            } else if (randomNumber < 0.1) {
              num *= 0.7;
              num2 *= 0.9;
              populationIncrease = Math.floor(Math.random() * num);
              populationIncrease2 = Math.floor(Math.random() * num2);
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              populationIncrease=parseInt(populationIncrease)
              populationIncrease2 += weizhi.金钱;
              let msg1 = `天降陨石，炸死了自己方人马，大幅度增加损失兵马，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
              team.兵=parseInt(team.兵)
              team.兵 -= populationIncrease;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
            } else if (randomNumber < 0.3) {
              num *= 0.3;
              num2 *= 0.1;
              populationIncrease = Math.floor(Math.random() * num);
              populationIncrease2 = Math.floor(Math.random() * num2);
              populationIncrease2 += weizhi.金钱;
              let msg1 = `我方士兵血气上涌，你轻松的战胜了对手，大幅度减少了损失，最终取得胜利，损失兵马${populationIncrease}，获得金钱${populationIncrease2}`;
              if (populationIncrease = undefined) {
                populationIncrease = 0
              }
              populationIncrease=parseInt(populationIncrease)
              team.兵=parseInt(team.兵)
              team.兵 -= populationIncrease;
              guojia.负债 += populationIncrease2;
              msg.push(msg1);
              for (let i = 0; i < 非零兵种列表.length; i++) {
                let msg2 = "其他兵种未损失";
                for (let a = 0; a < type.length; a++) {
                  for (let b = 0; b < type2.length; b++) {
                    if (非零兵种列表[i] === type[a]) {
                      if (randomNumber < 0.8) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.5));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    } else if (非零兵种列表[i] === type2[b]) {
                      if (randomNumber < 0.4) {
                        let x = team.兵种[非零兵种列表[i]];
                        let xx = Math.floor(Math.random() * (x * 0.3));
                        x -= xx;
                        msg2 = `损失${非零兵种列表[i]}${xx}`;
                      }
                    }
                  }
                }
                if (msg2 !== "其他兵种未损失") {
                  msg.push(msg2);
                }
              }
            }
            
          }
          
          team.状态 ="无"
      
          await Write_json(await getGuojiaIndex(player.国家), guojia);
          if (guojia.负债 < 0) {
            let msg2 =(`国家已负债${guojia.负债},请尽快还款`)
            msg.push(msg2);
          }
          
          await redis.del(`sanguo:${shuzhi}:${usr_qq}:action`);
          //发送消息
          let temp_data = {
            temp: msg,
          };
          const data1 = await new Show().get_jiesuanData(temp_data);
          let img = await puppeteer.screenshot('jiesuan', {
            ...data1,
          });
          e.reply(img);
          return;
      }
    }
    e.reply("搁这愁啥呢");
}